<template>
	<view class="wrap">
		<u-form class="form" :model="model" :rules="rules" ref="uForm" :label-position="labelPosition">
			<u-form-item label="应用名称" prop="agentId" label-width="180" :required="true">
				<js-select v-model="model.agentId" :items="agentDataList" itemLabel="name" itemValue="agentId"
					placeholder="请选择应用" :disabled="disabled || disabledChatId"></js-select>
			</u-form-item>
			<u-form-item label="消息类型" prop="msgType" label-width="180" :required="true">
				<js-select v-model="model.msgType" dict-type="wechat_group_message_type" itemLabel="dictValue"
					itemValue="dictKey" placeholder="请选择消息类型" :disabled="disabled"></js-select>
			</u-form-item>
			<u-form-item ref="uFormItemUserList" label="发送范围" prop="userList" label-width="180" label-position="top" :required="true">
				<view>
					<scroll-view :scroll-top="scrollTop" :scroll-y="scrollY" :class="{'scroll-Y': isScroll}"
						@scroll="scroll">
						<u-tag :text="item.name" :type="uTagProps.type" v-for="(item, index) in model.userList" 
							:key="item.userDeptId + '' + item.ownerType" :index="item.userDeptId" :shape="uTagProps.shape" 
							:closeable="uTagProps.closeable" :mode="uTagProps.mode" 
							:size="uTagProps.size" @close="doDeleteUser" class="uTagStyle"></u-tag>
					</scroll-view>
				</view>
				<u-button v-if="!isViewMode" slot="right" type="success" size="mini" @click="chooseDeptsOrUsers" style="">选择范围</u-button>
				<!--
				<js-choose-user-popup v-if="useInitChooseUserComp" ref="chooseDeptsOrUsers" @submit="useDeptsOrUsersSelected"
					:mode="popupGroupUsers.mode" :multiple="popupGroupUsers.multiple"
					:action="chooseUserUrl" :default-selected-user-list = "defaultGroupMemberUserList"></js-choose-user-popup>
				-->
				<!-- 使用支持组织、人员、标签选择的组件 -->
				<u-popup
					v-model="jsOrgOptions.show" 
					mode="bottom" 
					:zIndex="996" 
					height="100%" 
					:closeable="false"
				>
					<js-org 
						:data="jsOrgOptions.data"
						:label="'title'" 
						:node-type="'ownerType'" 
						:need-composite-key="true" 
						:select-types="jsOrgOptions.selectTypes"
						:is-show-icon="jsOrgOptions.isShowIcon"
						:is-multiple="jsOrgOptions.isMultiple"
						:default-show-type="jsOrgOptions.defaultShowType" 
						:selected-list="jsOrgOptions.selectedList"
						@on-submit="onOrgSubmit" 
						@on-cancel="onOrgCancel" 
						@on-expand="onOrgExpand"
						@on-nav="onOrgNav"
						@on-switch-show-type="onOrgSwitch"
					>
					</js-org>
				</u-popup>
			</u-form-item>
			<u-form-item label="保密消息" label-width="180">
				<u-switch v-model="uSwitchProps.checked" :loading="uSwitchProps.loading" :size="uSwitchProps.size"
					@change="uSwitchChange" :active-color="uSwitchProps.activeColor" :disabled="disabled"
					:activeValue="1" :inactiveValue="0"></u-switch>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'text'" label="文本内容" prop="text.content" label-width="180" label-position="top" :required="true">
				<u-input type="textarea" placeholder="请输入文本内容" v-model="model.text.content" height="100" maxlength="500" :disabled="disabled" />
			</u-form-item>
			<u-form-item v-if="model.msgType === 'image'" ref="uFormItemWechatUpload" label="上传图片(大小2M以下)" prop="tempVariable.isUploadedImage" label-width="180" label-position="top" :required="true">
				<text slot="labelCustomExtension">{{ currentSelectedFileCount }}/{{ upload.maxCount }}</text>
				<wechat-upload ref="wechatUpload" :form-data="{type:model.msgType}" :file-list="defaultFileList" upload-text="选择图片" accept="image" 
					:extension="upload.imageExt" :deletable="upload.deletable" :max-size="upload.maxSizeImage" 
					@on-success="onSuccessCallBack" @on-remove="onRemoveCallBack" @on-list-change="onListChangeCallBack"></wechat-upload>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'voice'" ref="uFormItemWechatUpload" label="上传音频(大小2M以下)" prop="tempVariable.isUploadedVoice" label-width="180" label-position="top" :required="true">
				<text slot="labelCustomExtension">{{ currentSelectedFileCount }}/{{ upload.maxCount }}</text>
				<wechat-upload ref="wechatUpload" :form-data="{type:model.msgType}" :file-list="defaultFileList" upload-text="选择音频" accept="file" 
					:extension="upload.voiceExt" :deletable="upload.deletable" :max-size="upload.maxSizeVoice" 
					@on-success="onSuccessCallBack" @on-remove="onRemoveCallBack" @on-list-change="onListChangeCallBack"></wechat-upload>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'video'" ref="uFormItemWechatUpload" label="上传视频(大小10M以下)" prop="tempVariable.isUploadedVideo" label-width="180" label-position="top" :required="true">
				<text slot="labelCustomExtension">{{ currentSelectedFileCount }}/{{ upload.maxCount }}</text>
				<wechat-upload ref="wechatUpload" :form-data="{type:model.msgType}" :file-list="defaultFileList" upload-text="选择视频" accept="video" 
					:extension="upload.videoExt" :deletable="upload.deletable" :max-size="upload.maxSizeVideo" 
					@on-success="onSuccessCallBack" @on-remove="onRemoveCallBack" @on-list-change="onListChangeCallBack"></wechat-upload>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'video'" label="标题" prop="video.title" label-width="180">
				<u-input type="text" placeholder="请输入标题" v-model="model.video.title" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'video'" label="描述" prop="video.description" label-width="180">
				<u-input type="text" placeholder="请输入描述" v-model="model.video.description" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'file'" ref="uFormItemWechatUpload" label="上传文件(大小20M以下)" prop="tempVariable.isUploadedFile" label-width="180" label-position="top" :required="true">
				<text slot="labelCustomExtension">{{ currentSelectedFileCount }}/{{ upload.maxCount }}</text>
				<wechat-upload ref="wechatUpload" :form-data="{type:model.msgType}" :file-list="defaultFileList" upload-text="选择文件" accept="file" 
					:deletable="upload.deletable" :max-size="upload.maxSizeFile" 
					@on-success="onSuccessCallBack" @on-remove="onRemoveCallBack" @on-list-change="onListChangeCallBack"></wechat-upload>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'textcard'" label="卡片标题" prop="textcard.title" label-width="180" :required="true">
				<u-input type="text" placeholder="请输入卡片标题" v-model="model.textcard.title" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'textcard'" label="卡片描述" prop="textcard.description" label-width="180" :required="true">
				<u-input type="text" placeholder="请输入卡片描述" v-model="model.textcard.description" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'textcard'" label="跳转链接" prop="textcard.url" label-width="180" :required="true">
				<u-input type="text" placeholder="请输入跳转链接" v-model="model.textcard.url" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'textcard'" label="按钮文字" prop="textcard.btntxt" label-width="180">
				<u-input type="text" placeholder="请输入按钮文字" v-model="model.textcard.btntxt" :disabled="disabled"></u-input>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'news'" label="图文消息" prop="news" label-width="180" label-position="top" left-icon="photo" :left-icon-style="{color:'#2979ff'}">
				<view style="margin-left: 50rpx;" :border-bottom="uFormItemPropsNews.borderBottom">
					<view v-for="(newsArticle, index) in model.news.articles" :key="index" :border-bottom="uFormItemPropsNews.borderBottom">
						<u-line class="u-line" :border-style="uLine.borderStyle" color="red" :color="uLine.color" :length="uLine.length" :direction="uLine.direction" :hair-line="uLine.hairLine"></u-line>
						<u-form-item :label="'标题'" :prop="'news.articles.title' + index" label-width="180" :required="true">
							<u-input type="text" placeholder="请输入标题" v-model="newsArticle.title" height="100" maxlength="500" :disabled="disabled" />
						</u-form-item>
						<u-form-item label="跳转链接" :prop="'news.articles.url' + index" label-width="180" :required="true">
							<u-input type="text" placeholder="请跳转链接" v-model="newsArticle.url" height="100" maxlength="500" :disabled="disabled" />
						</u-form-item>
						<u-form-item label="描述" prop="news.articles.description" label-width="180">
							<u-input type="text" placeholder="请描述" v-model="newsArticle.description" height="100" maxlength="500" :disabled="disabled" />
						</u-form-item>
						<u-form-item label="图片链接" prop="news.articles.picurl" label-width="180">
							<u-input type="text" placeholder="请输入图片链接" v-model="newsArticle.picurl" height="100" maxlength="500" :disabled="disabled" />
						</u-form-item>
						<u-form-item label-width="180" v-if="!isViewMode">
							<u-button slot="right" type="primary" size="mini" @click="deleteNewsArticles(index)">删除</u-button>
						</u-form-item>
					</view>
				</view>
			</u-form-item>
			<u-form-item v-if="model.msgType === 'markdown'" label="MarkDown" prop="markdown.content" label-width="180" label-position="top" :required="true">
				<u-input type="textarea" placeholder="请输入markdown内容" v-model="model.markdown.content" height="100" maxlength="500" :disabled="disabled" />
			</u-form-item>
		</u-form>
		<view v-if="(model.msgType === 'news') && !isViewMode" class="my-btn-plus" @click="addNewsArticles">
			<u-icon name="plus-circle-fill" size="90" color="#3d87ff"></u-icon>
		</view>
		<slot name="footerBtns">
			<view style="display: flex;flex-direction: row;">
				<u-button v-if="!isViewMode" class="btn" style="width: 50%;margin-right: 10rpx;" type="primary" @click="submit">保存</u-button>
				<u-button class="btn" style="width: 50%;" @click="cancel">
					{{isViewMode ? '返回' : '取消'}}
				</u-button>
			</view>
		</slot>
	</view>
</template>
<script>
	import { Base64 } from '@/common/base64.js'
	import WechatUpload from '@/pages/wechat/wechat-upload.vue'
	export default {
		components: {
			WechatUpload
		},
		props: {
			// 当前组件被使用的来源标识，如：popup(表示弹出层方式被调用)
			usedSource:{
				type: String,
				default: ''
			},
			agentId:{
				type: String,
				default: ''
			},
			disabledChatId: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				model: {
					agentId: '',
					msgType: 'text',
					safe: 0,
					userList: [],
					text: {
						content: ''
					},
					image: {
						media_id: ''
					},
					voice: {
						media_id: ''
					},
					video: {
						media_id: '',
						title: '',
						description: ''
					},
					file: {
						media_id: ''
					},
					textcard: {
						title: '',
						description: '',
						url: '',
						btntxt: ''
					},
					news: {
						articles: [{
							title: "",
							description: "",
							url: "",
							picurl: ""
						}]
					},
					markdown: {
						content: ''
					}
				},
				isModelLoadedFlag: false,
				// 操作模式：view、add、edit
				mode: '',
				agentDataList: [],
				uSwitchProps: {
					checked: false,
					activeColor: '#2979ff',
					size: 50,
					loading: false,
					disabled: false
				},
				// 修改前最初的msgType
				editModePrimaryMsgType: '',
				//默认已有文件列表
				defaultFileList: [],
				//标识当前已上传的文件数
				currentSelectedFileCount: 0,
				upload: {
					deletable: true,
					imageExt: ['.jpg','.png'],
					voiceExt: ['.arm'],
					videoExt: ['.mp4'],
					maxCount: 1,
					maxSizeImage: 2 * 1024 * 1024,
					maxSizeVoice: 2 * 1024 * 1024,
					maxSizeVideo: 10 * 1024 * 1024,
					maxSizeFile: 20 * 1024 * 1024
				},
				isViewMode: false,
				labelPosition: 'left',
				disabled: true,
				uFormItemPropsNews: {
					borderBottom: false
				},
				uLine: {
					direction: 'row',
					hairLine: false,
					length: '100%',
					color: this.$u.color['primary'],
					borderStyle: 'dashed'
				},
				uTagProps: {
					mode: 'light',
					type: 'primary',
					size: 'default',
					shape: 'square',
					closeable: true
				},
				isScroll: true,
				scrollTop: 0,
				scrollY: true,
				old: {
					scrollTop: 0
				},
				chooseUserUrl: '/api/blade-system/user/user-list-by-dept-type',
				popupGroupUsers: {
					show: false,
					mode: "bottom",
					multiple: true,
				},
				jsOrgOptions: {
					show: false,
					// 默认显示类型
					defaultShowType: "org",
					// 控制单/多选变量
					isMultiple: true,
					// 数据源
				    data: [],
					// 控制头像显隐的变量
					isShowIcon: true,
					selectTypes: ['1', '2', '3'],
					selectedList: []
				},
				rules: {
					agentId: [{
						required: true,
						message: '请选择应用',
						trigger: 'change'
					}],
					msgType: [{
						required: true,
						message: '请选择消息类型',
						trigger: 'change'
					}],
					userList: [{
						required: true,
						message: '请选择发送范围',
						trigger: 'change',
						type: 'array'
					}],
					safe: [{
						required: true,
						message: '请选择保密类型',
						trigger: ['change', 'blur']
					}],
					'text.content': [{
						required: true,
						message: '请填写文本内容',
						trigger: ['change', 'blur']
					}],
					'tempVariable.isUploadedImage':[{
						validator: (rule, value, callback) => {
							let fileList = this.getFileList();
							return fileList.length > 0;
						},
						message: '请上传图片',
						trigger: ['change','blur']
					}],
					'tempVariable.isUploadedVoice':[{
						validator: (rule, value, callback) => {
							let fileList = this.getFileList();
							return fileList.length > 0;
						},
						message: '请上传音频',
						trigger: ['change','blur']
					}],
					'tempVariable.isUploadedVideo':[{
						validator: (rule, value, callback) => {
							let fileList = this.getFileList();
							return fileList.length > 0;
						},
						message: '请上传视频',
						trigger: ['change','blur']
					}],
					'tempVariable.isUploadedFile':[{
						validator: (rule, value, callback) => {
							let fileList = this.getFileList();
							return fileList.length > 0;
						},
						message: '请上传文件',
						trigger: ['change','blur']
					}],
					'textcard.title': [{
						required: true,
						message: '请填写卡片标题',
						trigger: ['change', 'blur']
					}],
					'textcard.description': [{
						required: true,
						message: '请填写卡片描述',
						trigger: ['change', 'blur'],
					}],
					'textcard.url': [{
						required: true,
						message: '请填写跳转链接',
						trigger: ['change', 'blur']
					}],
					'news.articles.title0': [{
						tempRuleIndex: 0,
						validator: (rule, value, callback) => {
							// 判断model.news.articles中的对象是否存在title为空
							let tempRuleIndex = rule.tempRuleIndex;
							let isNull = this.model.news.articles.some((article,index) => tempRuleIndex == index && !article.title);
							return !isNull;
						},
						message: '请填写标题',
						trigger: ['change', 'blur']
					}],
					'news.articles.url0': [{
						tempRuleIndex: 0,
						validator: (rule, value, callback) => {
							// 判断model.news.articles中的对象是否存在url为空
							let tempRuleIndex = rule.tempRuleIndex;
							let isNull = this.model.news.articles.some((article,index) => tempRuleIndex == index && !article.url);
							return !isNull;
						},
						message: '请填写跳转链接',
						trigger: ['change', 'blur']
					}],
					'markdown.content': [{
						required: true,
						message: '请填写markdown内容',
						trigger: ['change', 'blur']
					}]
				}
			};
		},
		computed: {
			/**
			 * 返回是否初始化选择用户组件的标识
			 * 解决父组件将请求回来的数据传递给子组件的延迟问题
			 */
			useInitChooseUserComp: function(){
				let useInit = false;
				if(this.mode === 'add' || (this.mode === 'edit' && this.isModelLoadedFlag)){
					useInit = true;
				}
				return useInit;
			},
			defaultGroupMemberUserList: function(){
				let userList = this.model.userList;
				return userList;
			}
		},
		watch: {
			'model.safe': function(val, oldVal) {
				if (val == 1) {
					this.uSwitchProps.checked = true;
				} else {
					this.uSwitchProps.checked = false;
				}
			},
			'model.userList': function(val,oldVal){
				// 触发u-form-item(uFormItemUserList)组件实例的on-form-change事件
				this.$refs.uFormItemUserList.$emit('on-form-change', val);
			},
			'model.msgType': function(val,oldVal){
				const msgTypeRelRequiredFieldProps = {
					'text':['text.content'],
					'image': ['tempVariable.isUploadedImage'],
					'voice': ['tempVariable.isUploadedVoice'],
					'video': ['tempVariable.isUploadedVideo'],
					'file': ['tempVariable.isUploadedFile'],
					'textcard': ['textcard.title','textcard.description','textcard.url'],
					'news': [],
					'markdown': ['markdown.content']
				};
				let needResetFiledProps = [];
				if(oldVal){
					needResetFiledProps = msgTypeRelRequiredFieldProps[oldVal];
				}
				// 移除上一个消息类型对应的form-item检验结果
				if(needResetFiledProps.length > 0){
					this.$refs.uForm.fields.map(field => {
						if(needResetFiledProps.includes(field.prop)){
							field.resetField();
						}
					});
				}
				// 修改模式时，当前消息类型不是editModePrimaryMsgType时，则将defaultFileList初始为空数组
				if(this.mode == 'edit' && this.editModePrimaryMsgType != val){
					// defaultFileList初始为空数组
					this.defaultFileList = [];
					// 同时还要清空上传组件的内部文件列表，因为上面defaultFileList虽然置为空了，但是目前上传组件还是有数据显示，说明有脏数据
					if(this.$refs.wechatUpload){
						this.$refs.wechatUpload.clearFileList();
					}
				}
			},
			defaultFileList: function(val,oldVal){
				if(val && val.length && val.length > 0){
					this.currentSelectedFileCount = val.length;
				}
			},
			'jsOrgOptions.defaultShowType': {
				handler(showType) {
					this.loadOrgDataList();
				},
				immediate: true,
				deep: true
			}
		},
		onLoad(params) {
			this.initAgentDataList();
			this.initData(params);
		},
		created() {
			let usedSource = this.usedSource,agentId = this.agentId;
			if(usedSource === 'popup' && agentId){
				if(this.agentDataList.length == 0){
					// agentDataList为空需进行初始操作
					this.initAgentDataList();
				}
				this.model.agentId = agentId;
				this.disabled = false;
			}
		},
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		},
		mounted(){
			let usedSource = this.usedSource,agentId = this.agentId;
			if(usedSource === 'popup' && agentId){
				this.$refs.uForm.setRules(this.rules);
			}
		},
		methods: {
			initData(params){
				let vm = this;
				this.mode = params.mode;
				if (params.id) {
					if (this.mode == "view") {
						this.disabled = true;
						this.isViewMode = true;
						this.upload.deletable = false;
						this.uTagProps.closeable = false;
					} else {
						this.disabled = false;
						this.isViewMode = false;
						this.upload.deletable = true;
						this.uTagProps.closeable = true;
					}
					this.$u.api.wechat.wechatAgentNotice.detail({
						id: params.id
					}).then(res => {
						Object.assign(vm.model, res.data);
						vm.editModePrimaryMsgType = vm.model.msgType;
						vm.initFillMsgTypeRelContent();
					});
				} else {
					this.disabled = false;
				}
			},
			initAgentDataList() {
				this.$u.api.wechat.wechatAgent.getAgentAllDict().then(res => {
					if (res.success) {
						this.agentDataList = res.data;
					}
				});
			},
			doDeleteUser: function(userDeptId) {
				this.model.userList = this.model.userList.filter(user => userDeptId != user.userDeptId);
				// this.$refs.chooseDeptsOrUsers.$emit('remove-selected-user-by-id',userDeptId);
			},
			submit() {
				let vm = this;
				this.$refs.uForm.validate(valid => {
					if (valid) {
						uni.showLoading({
							title: '提交中....'
						})
						this.doBeforeModelPost();
						this.$u.api.wechat.wechatAgentNotice.save(this.model).then(res => {
							uni.hideLoading();
							uni.showModal({
								title: '提示',
								content: res.msg,
								showCancel: false,
								success: function() {
									if (res.code == 200) {
										uni.setStorageSync('refreshWecahtAgentNoticeList', true);
										uni.navigateBack();
									}
								}
							});
						});
					} else {
						this.$u.toast('您填写的信息有误，请根据提示修正。');
					}
				});
			},
			cancel() {
				uni.navigateBack();
			},
			confirm(e) {
				this.model.revokeTime = '';
				if (this.params.year) {
					this.model.revokeTime += e.year;
				}
				if (this.params.month) {
					this.model.revokeTime += '-' + e.month;
				}
				if (this.params.day) {
					this.model.revokeTime += '-' + e.day;
				}
				if (this.params.hour) {
					this.model.revokeTime += ' ' + e.hour;
				}
				if (this.params.minute) {
					this.model.revokeTime += ':' + e.minute;
				}
				if (this.params.second) {
					this.model.revokeTime += ':' + e.second;
				}
				this.show = false;
			},
			chooseDeptsOrUsers() {
				// this.$refs.chooseDeptsOrUsers.open();
				if(this.model.userList.length > 0){
					// 先重置jsOrgOptions.selectedList
					this.jsOrgOptions.selectedList = [];
					// 再将model.userList中的数据转化成jsOrgOptions.selectedList的数据，以便js-org组件回填
					this.model.userList.forEach(user => {
						this.jsOrgOptions.selectedList.push({
							id: user.userDeptId,
							ownerType: user.ownerType,
							title: user.name
						});
					})
				}
				this.jsOrgOptions.show = true;
				this.loadOrgDataList();
			},
			useDeptsOrUsersSelected() {
				//目前发送范围只支持选人
				let users = this.$refs.chooseDeptsOrUsers.getData();
				if (users.length > 0) {
					this.model.userList = [];
				}
				//ownerType: 1 部门、2 用户、3 标签
				users.forEach((element) => {
					this.model.userList.push({
						"ownerType": 2,
						"userDeptId": element.id,
						"name": element.name
					});
				});
				this.$refs.chooseDeptsOrUsers.close();
			},
			scroll: function(e) {
				this.old.scrollTop = e.detail.scrollTop
			},
			uSwitchChange(value) {
				this.model.safe = value;
			},
			
			/**
			 * 初始回填消息类型关联的内容
			 */
			initFillMsgTypeRelContent() {
				let msgType = this.model.msgType;
				let content = this.model.content;
				if (content) {
					content = JSON.parse(content);
				}
				if (msgType === 'text') {
					this.model.text = content;
				} else if (msgType === 'image') {
					this.model.image = content;
					this.defaultFileList.push(this.model.image);
				} else if (msgType === 'voice') {
					this.model.voice = content;
					this.defaultFileList.push(this.model.voice);
				} else if (msgType === 'video') {
					this.model.video = content;
					this.defaultFileList.push(this.model.video);
				} else if (msgType === 'file') {
					this.model.file = content;
					this.defaultFileList.push(this.model.file);
				} else if (msgType === 'textcard') {
					this.model.textcard = content;
				} else if (msgType === 'news') {
					this.model.news = content;
				} else if (msgType === 'markdown') {
					this.model.markdown = content;
				}
			},
			onSuccessCallBack(data, index, lists){
				// 手动触发u-form-item组件实例（uFormItemWechatUpload）的on-form-change事件
				this.$refs.uFormItemWechatUpload.$emit('on-form-change');
			},
			onRemoveCallBack(data, index, lists){
				// 手动触发u-form-item组件实例（uFormItemWechatUpload）的on-form-change事件
				this.$refs.uFormItemWechatUpload.$emit('on-form-change');
			},
			onListChangeCallBack(lists) {
				// console.log("onListChangeCallBack lists: %s",lists.length);
				this.currentSelectedFileCount = lists.length;
			},
			getFileList() {
				let files = this.$refs.wechatUpload.getFileList();
				let fileList = [];
				files.forEach(item => {
					if(item.response && item.response.data){
						//当前新上传的文件
						let data = item.response.data;
						const { mediaId, link, originalName } = data;
						fileList.push({
							media_id: mediaId,
							url: link,
							name: originalName
						});
					}else{
						//默认已有的文件
						const {name,url} = item;
						let mediaId = '';
						let found = this.defaultFileList.find(element => element.url == url);
						if(found){
							mediaId = found.media_id || '';
						}
						fileList.push({
							media_id: mediaId,
							url: url,
							name: name
						});
					}
				})
				return fileList;
			},
			doBeforeModelPost() {
				// 1. 构建model.content数据
				let msgType = this.model.msgType;
				if (msgType === 'text') {
					this.model.content = JSON.stringify(this.model.text);
				} else if (msgType === 'image') {
					let modelImage = this.model.image;
					let content = this.$u.deepMerge(modelImage, this.getFileList()[0]);
					this.model.content = JSON.stringify(content);
				} else if (msgType === 'voice') {
					let modelVoice = this.model.voice;
					let content = this.$u.deepMerge(modelVoice, this.getFileList()[0]);
					this.model.content = JSON.stringify(content);
				} else if (msgType === 'video') {
					let modelVideo = this.model.video;
					let content = this.$u.deepMerge(modelVideo, this.getFileList()[0]);
					this.model.content = JSON.stringify(content);
				} else if (msgType === 'file') {
					let modelFile = this.model.file;
					let content = this.$u.deepMerge(modelFile, this.getFileList()[0]);
					this.model.content = JSON.stringify(content);
				} else if (msgType === 'textcard') {
					this.model.content = JSON.stringify(this.model.textcard);
				} else if (msgType === 'news') {
					this.model.content = JSON.stringify(this.model.news);
				} else if (msgType === 'markdown') {
					this.model.content = JSON.stringify(this.model.markdown);
				}
			},
			addNewsArticles() {
				this.model.news.articles.push(
					{
						title: "",
						description: "",
						url: "",
						picurl: ""
					}
				);
				this.addNewsArticlesRules();
			},
			addNewsArticlesRules() {
				let tempRuleIndex = this.model.news.articles.length - 1;
				let ruleTitle = this.rules["news.articles.title0"];
				// 深度克隆
				let ruleTitleClone = this.$u.deepClone(ruleTitle);
				ruleTitleClone[0].tempRuleIndex = tempRuleIndex;
				let ruleTitleKey = "news.articles.title" + tempRuleIndex;
				this.rules[ruleTitleKey] = ruleTitleClone;
				
				let ruleUrl = this.rules["news.articles.url0"];
				let ruleUrlClone = this.$u.deepClone(ruleUrl);
				ruleUrlClone[0].tempRuleIndex = tempRuleIndex;
				let ruleUrlKey = "news.articles.url" + tempRuleIndex;
				this.rules[ruleUrlKey] = ruleUrlClone;
			},
			//上传文件相关
			deleteNewsArticles(index) {
				let vm = this;
				uni.showModal({
					title: '提示',
					content: '确定删除吗？',
					showCancel: true,
					success: function(res) {
						if (res.confirm) {
							vm.model.news.articles.splice(index,1);
						}
					}
				});
			},
			// 组织、人员、标签选择组件的相关事件
			/**
			 * 组件数据提交
			 * @param {Object} selectedItems
			 */
			onOrgSubmit(selectedItems) {
				if(typeof selectedItems === 'undefined') {
					selectedItems = [];
				}else if(selectedItems.length > 0) {
					// 如果回传的数据不为空，则需要将表单model的userList重置为空
					this.model.userList = [];
				}
				// ownerType: 1 部门、2 用户、3 标签
				selectedItems.forEach((element) => {
					this.model.userList.push({
						"ownerType": element.ownerType,
						"userDeptId": element.id,
						"name": element.title
					});
				});
				this.jsOrgOptions.show = false;
			},
			
			/**
			 * 关闭
			 */
			onOrgCancel() {
				this.jsOrgOptions.show = false;
			},
		
			/**
			 * 右侧箭头点击事件
			 * @param {Object} data
			 */
			onOrgExpand(data) {
				let { id } = data;
				this.loadOrgDataList(id);
			},
		
			/**
			 * 面包屑导航点击事件
			 * @param {Object} data
			 */
			onOrgNav(data) {
			  // data == -1 为点击全部的时候，否则是点击导航栏
			  if (data == -1) {
				this.loadOrgDataList();
			  } else {
				this.loadOrgDataList(data.id);
			  }
			},
		
			/**
			 * 切换显示类型事件
			 * @param {Object} showType
			 */
			onOrgSwitch(showType) {
				this.jsOrgOptions.defaultShowType = showType;
			},
		
			/**
			 * 获取数据
			 */
			loadOrgDataList(parentId) {
				if (this.jsOrgOptions.defaultShowType == "org") {
					this.$u.api.dept.deptUserLazyTree({
						parentId: parentId || 0
					}).then(res => {
						this.jsOrgOptions.data = res.data;
					});
				} else {
					this.$u.api.wechat.wechatAgentNotice.wechatTagTree().then(res => {
						this.jsOrgOptions.data = res.data;
						if(Array.isArray(this.jsOrgOptions.data) && this.jsOrgOptions.data.length > 0) {
							this.jsOrgOptions.data.forEach((item) => {
								// 补充标签对象的ownerType属性
								item.ownerType = '3';
							})
						}
					});
				}
			}
		}
	};
</script>
<style lang="scss" scoped>
	.wrap {
		padding: 30rpx;
	}

	.uTagStyle {
		margin-right: 10rpx;
	}

	.scroll-Y {
		height: 200rpx;
	}
	
	.my-btn-plus{
		position: absolute;
		top: 30%;
		right: 50rpx;
		z-index: 10;
		opacity: 0.6;
	}
	
	.my-btn-plus:hover {
		opacity: 1;
	}

	/deep/ ::-webkit-scrollbar {
		/*滚动条整体样式*/
		width: 4px !important;
		height: 1px !important;
		overflow: auto !important;
		background: #ccc !important;
		-webkit-appearance: auto !important;
		display: block;
	}

	/deep/ ::-webkit-scrollbar-thumb {
		/*滚动条里面小方块*/
		border-radius: 10px !important;
		box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2) !important;
		background: #7b7979 !important;
	}

	/deep/ ::-webkit-scrollbar-track {
		/*滚动条里面轨道*/
		background: #FFFFFF !important;
	}
</style>